package com.shenhan.assistclass;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * @Author shenhan
 * @Date: 2020/6/10 22:34
 * @Description:
 */
public class SemaPhoreDemo {
    public static void main(String[] args) {
        // 假设有3个停车位
        Semaphore semaphore = new Semaphore(3);
        // 有6辆车要停车
        IntStream.range(1, 7).forEach(i -> new Thread(() -> {
            try {
                semaphore.acquire();
                System.out.println(Thread.currentThread().getName() + " ----抢到车位");
                TimeUnit.SECONDS.sleep(2L);
                System.out.println(Thread.currentThread().getName() + " ----离开车位");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release();
            }
        }, String.valueOf(i)).start());
    }
}
